//输入两棵二叉树A和B，判断B是不是A的子结构。(约定空树不是任意一个树的子结构) 
//
// B是A的子结构， 即 A中有出现和B相同的结构和节点值。 
//
// 例如: 
//给定的树 A: 
//
// 3 
// / \ 
// 4 5 
// / \ 
// 1 2 
//给定的树 B： 
//
// 4 
// / 
// 1 
//返回 true，因为 B 与 A 的一个子树拥有相同的结构和节点值。 
//
// 示例 1： 
//
// 输入：A = [1,2,3], B = [3,1]
//输出：false
// 
//
// 示例 2： 
//
// 输入：A = [3,4,5,1,2], B = [4,1]
//输出：true 
//
// 限制： 
//
// 0 <= 节点个数 <= 10000 
// Related Topics 树 深度优先搜索 二叉树 👍 590 👎 0


package leetcode.editor.cn;

import com.leetcode.utils.TreeNode;

//Java：树的子结构
public class ShuDeZiJieGouLcof {
    public static void main(String[] args) {
        Solution solution = new ShuDeZiJieGouLcof().new Solution();
        // TO TEST
        TreeNode A = new TreeNode(4);
        A.left = new TreeNode(2);
        A.right = new TreeNode(3);
        A.left.left = new TreeNode(4);
        A.left.right = new TreeNode(5);
        A.right.left = new TreeNode(6);
        A.right.right = new TreeNode(7);
        A.left.left.left = new TreeNode(8);
        A.left.left.right = new TreeNode(9);
        TreeNode B = new TreeNode(4);
        B.left = new TreeNode(8);
        B.right = new TreeNode(9);

        System.out.println(solution.isSubStructure(A, B));
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        /**
         * 输入两棵二叉树A和B，判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
         *
         * @param A
         * @param B
         * @return
         */
        public boolean isSubStructure(TreeNode A, TreeNode B) {
            if (B == null || A == null) {
                return false;
            }
            return traverTree(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
        }

        public boolean traverTree(TreeNode A, TreeNode B) {
            // B已经遍历结束了就算返回true
            if (B == null) {
                return true;
            }
            if (A == null || A.val != B.val) {
                return false;
            }
            return traverTree(A.left, B.left) && traverTree(A.right, B.right);
        }

        public boolean isSubStructure2(TreeNode A, TreeNode B) {
            return (A != null && B != null) && (recur2(A, B) || isSubStructure2(A.left, B) || isSubStructure2(A.right, B));
        }
        boolean recur2(TreeNode A, TreeNode B) {
            // B已经遍历结束了
            if(B == null) {
                return true;
            }
            if(A == null || A.val != B.val) {
                return false;
            }
            return recur2(A.left, B.left) && recur2(A.right, B.right);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
